package com.byComputer.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具类
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-28
 */
public class CookieUtils {

	/** 应用地址 */
	private static final String path = "/byComputer";

	/** 设置默认的cookie最大存活时间是一个星期 */
	private static final int maxAge = 60 * 60 * 24 * 7;

	/**
	 * 添加cookie到response里面
	 * 
	 * @addCookie
	 * @param name
	 * @param path
	 * @param maxAge
	 * @param value
	 * @param response
	 */
	public static void addCookie(String name, String path, int maxAge,
			String value, HttpServletResponse response) {

		try {
			Cookie cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
			cookie.setPath(path);
			cookie.setMaxAge(maxAge);
			response.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @addCookie
	 * @param name
	 * @param value
	 * @param response
	 */
	public static void addCookie(String name, String value,
			HttpServletResponse response) {
		addCookie(name, path, maxAge, value, response);
	}

	/**
	 * @delete
	 * @param name
	 * @param response
	 */
	public static void delete(String name, HttpServletResponse response) {
		Cookie cookie = new Cookie(name, "");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

	/**
	 * 得到cookie
	 * 
	 * @findCookie
	 * @param name
	 * @param value
	 * @param response
	 * @return
	 */
	public static String findCookie(String name, String value,
			HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String value1 = null;
		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				value1 = cookie.getValue();
				break;
			}
		}
		if (value1 != null) {

		}
		return value1;
	}

	/**
	 * 编码
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String enCoding(String str)
			throws UnsupportedEncodingException {
		String value = URLEncoder.encode(str, "utf-8");
		return value;
	}

	/**
	 * 解码
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String deCoding(String str)
			throws UnsupportedEncodingException {
		String value = URLDecoder.decode(str, "utf-8");
		return value;
	}

}
